package org.example.file.config;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.IdUtil;
import com.google.common.base.Joiner;
import io.minio.BucketExistsArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Slf4j
@RestController
@RequestMapping(value = "/file")
@CrossOrigin(origins = "*")
public class FileUploadController {

  private final MinioClient minioClient;

  public FileUploadController(MinioClient minioClient) {
    this.minioClient = minioClient;
  }

  @PostMapping("/upload")
  @SneakyThrows
  public String uploadFile(@RequestParam("file") MultipartFile file,
                           @RequestParam(required = false,defaultValue = "public",name = "bucket") String bucket,
                           @RequestParam(required = false,defaultValue = "public",name = "path") String path) {
    if (file.isEmpty()) {
      throw new RuntimeException("请上传文件！");
    }
    BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(bucket).build();
    boolean exists = minioClient.bucketExists(bucketExistsArgs);
    if(!exists){
      throw new RuntimeException("bucket不存在");
    }

    String suffix = "";
    long fileId = IdUtil.getSnowflakeNextId();
    String fileName = file.getOriginalFilename();
    if (fileName != null) {
      int dotIndex = fileName.lastIndexOf('.');
      if (dotIndex != -1) {
        suffix = fileName.substring(dotIndex + 1);
      }
    }
    String objectName = fileId + "." + suffix;
    String object = Joiner.on("/").join(CharSequenceUtil.split(path, ",")) + "/" + objectName;
    try(InputStream stream = file.getInputStream()) {
      minioClient.putObject(
              PutObjectArgs.builder()
                      .stream(stream, stream.available(), -1)
                      .bucket(bucket)
                      .object(object)
                      .contentType("application/octet-stream")
                      .build()
      );
    }
    return "/" + bucket + "/" + object;
  }
}
